package com.org.util.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Method;

import com.org.msmvc.sys.service.SystemControllerLog;
import com.org.msmvc.sys.service.SystemServiceLog;

import javassist.ClassClassPath;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.Modifier;
import javassist.NotFoundException;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 操作日志
 * 
 * @author zsh
 * @since 2014-08-05 Pm 20:35
 * @version 1.0
 */

@Component
@Aspect
public class SystemLogAspect {
	// 注入Service用于把日志保存数据库
	// @Resource
	// private LogService logService;
	// 本地异常日志记录对象
	private static final Logger logger = LoggerFactory.getLogger(SystemLogAspect.class);
	private static String[] types = { "java.lang.Integer", "java.lang.Double", "java.lang.Float", "java.lang.Long",
			"java.lang.Short", "java.lang.Byte", "java.lang.Boolean", "java.lang.Char", "java.lang.String", "int",
			"double", "long", "short", "byte", "boolean", "char", "float" };

	/**
	 * 
	 * 定义一个切入点.
	 * 
	 * 解释下：
	 *
	 * 
	 * 
	 * ~ 第一个 * 代表任意修饰符及任意返回值.
	 * 
	 * ~ 第二个 * 任意包名
	 * 
	 * ~ 第三个 * 代表任意方法.
	 * 
	 * ~ 第四个 * 定义在web包或者子包
	 * 
	 * ~ 第五个 * 任意方法
	 * 
	 * ~ .. 匹配任意数量的参数.
	 * 
	 */
	// Controller层切点
	@Pointcut("execution(* com.org.msmvc.sys.controller..*.*(..))")
	public void controllerAspect() {
	}

	/**
	 * 后置通知 用于拦截Controller层记录用户的操作
	 * 
	 * @param joinPoint
	 *            切点
	 */
	@After("controllerAspect()")
	public void after(JoinPoint joinPoint) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		HttpSession session = request.getSession();
		// 读取session中的用户
		String operater = (String) session.getAttribute("currentUser");
		// 请求的IP
		String ip = request.getRemoteAddr();
		try {
			String targetName = joinPoint.getTarget().getClass().getName(); // 类的名字
			String methodName = joinPoint.getSignature().getName(); // 方法名字
			Class targetClass = Class.forName(targetName);
			String operationType = "";
			Map<String, String[]> getParams = request.getParameterMap(); // 获取参数信息
			StringBuilder sb = new StringBuilder();
			String values = "";
			Map<String, Object> params = new HashMap<String, Object>();
			for (String key : getParams.keySet()) {
				values = Arrays.toString(getParams.get(key));
				params.put(key, values.substring(1, values.lastIndexOf("]")));
				sb.append(values.substring(1, values.lastIndexOf("]")));
				 sb.append("、");
			}
			System.out.println("------------------------" + sb.toString());
			// *========控制台输出=========*//
			System.out.println("=====controller后置通知开始=====");
			System.out.println("请求方法:"
					+ (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()")
					+ "." + operationType);

			System.out.println("方法描述:" + joinPoint.getSignature().getName());
			System.out.println("操作内容:" + params.get("name"));
			System.out.println("操作人:" + operater);
			System.out.println("请求IP:" + ip);

			System.out.println("=====controller后置通知结束=====");
		} catch (Exception e) {
			// 记录本地异常日志
			logger.error("==后置通知异常==");
			logger.error("异常信息:{}", e.getMessage());
		}
	}

	// 抛出异常时才调用
	@AfterThrowing("controllerAspect()")
	public void afterThrowing() {
		System.out.println("校验token出现异常了......");
	}
	// 配置controller环绕通知,使用在方法aspect()上注册的切入点

	/**
	 * 异常通知 用于拦截service层记录异常日志
	 * 
	 * @param joinPoint
	 * @param e
	 */
	/*
	 * @After("controllerAspect()") public void doAfterThrowing(JoinPoint
	 * joinPoint, Throwable e) { HttpServletRequest request =
	 * ((ServletRequestAttributes)
	 * RequestContextHolder.getRequestAttributes()).getRequest(); HttpSession
	 * session = request.getSession(); //读取session中的用户 String currentUser =
	 * (String)session.getAttribute("currentUser"); //获取请求ip String ip =
	 * request.getRemoteAddr(); //获取用户请求方法的参数并序列化为JSON格式字符串 String params = "";
	 * if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) { for
	 * ( int i = 0; i < joinPoint.getArgs().length; i++) { params +=
	 * joinPoint.getArgs()[i].toString() + ";"; } } try { ========控制台输出=========
	 * System.out.println("=====异常通知开始====="); System.out.println("异常代码:" +
	 * e.getClass().getName()); System.out.println("异常信息:" + e.getMessage());
	 * System.out.println("异常方法:" + (joinPoint.getTarget().getClass().getName()
	 * + "." + joinPoint.getSignature().getName() + "()"));
	 * System.out.println("方法描述:" + getServiceMthodDescription(joinPoint));
	 * System.out.println("请求人:" + currentUser); System.out.println("请求IP:" +
	 * ip); System.out.println("请求参数:" + params); ==========数据库日志========= Log
	 * log = new Log();
	 * log.setDescription(getServiceMthodDescription(joinPoint));
	 * log.setExceptionCode(e.getClass().getName()); log.setType(1);
	 * log.setExceptionDetail(e.getMessage());
	 * log.setMethod((joinPoint.getTarget().getClass().getName() + "." +
	 * joinPoint.getSignature().getName() + "()")); log.setParams(params);
	 * log.setCreateBy(currentUser); log.setCreateDate(new Date());
	 * log.setRequestIp(ip); //保存数据库 // logService.add(log);
	 * System.out.println("=====异常通知结束====="); } catch (Exception ex) {
	 * //记录本地异常日志 logger.error("==异常通知异常=="); logger.error("异常信息:{}",
	 * ex.getMessage()); } ==========记录本地异常日志==========
	 * logger.error("异常方法:{}异常代码:{}异常信息:{}参数:{}",
	 * joinPoint.getTarget().getClass().getName() +
	 * joinPoint.getSignature().getName(), e.getClass().getName(),
	 * e.getMessage(), params);
	 * 
	 * }
	 */

	/**
	 * 获取注解中对方法的描述信息 用于service层注解
	 * 
	 * @param joinPoint
	 *            切点
	 * @return 方法描述
	 * @throws Exception
	 */
	public static String getServiceMthodDescription(JoinPoint joinPoint) throws Exception {
		String targetName = joinPoint.getTarget().getClass().getName();
		String methodName = joinPoint.getSignature().getName();
		Object[] arguments = joinPoint.getArgs();
		Class targetClass = Class.forName(targetName);
		Method[] methods = targetClass.getMethods();
		String description = "";
		for (Method method : methods) {
			if (method.getName().equals(methodName)) {
				Class[] clazzs = method.getParameterTypes();
				if (clazzs.length == arguments.length) {
					description = method.getAnnotation(SystemServiceLog.class).description();
					break;
				}
			}
		}
		return description;
	}

	/**
	 * 获取注解中对方法的描述信息 用于Controller层注解
	 * 
	 * @param joinPoint
	 *            切点
	 * @return 方法描述
	 * @throws Exception
	 */
	public static String getControllerMethodDescription(JoinPoint joinPoint) throws Exception {
		String targetName = joinPoint.getTarget().getClass().getName();
		String methodName = joinPoint.getSignature().getName();
		Object[] arguments = joinPoint.getArgs();
		Class targetClass = Class.forName(targetName);
		Method[] methods = targetClass.getMethods();
		String description = "";
		for (Method method : methods) {
			if (method.getName().equals(methodName)) {
				Class[] clazzs = method.getParameterTypes();
				if (clazzs.length == arguments.length) {
					description = method.getAnnotation(SystemControllerLog.class).description();
					break;
				}
			}
		}
		return description;
	}


	/**
	 * 得到方法参数的名称
	 * 
	 * @param cls
	 * @param clazzName
	 * @param methodName
	 * @return
	 * @throws NotFoundException
	 */
	private static String[] getFieldsName(Class cls, String clazzName, String methodName) throws NotFoundException {
		ClassPool pool = ClassPool.getDefault();
		// ClassClassPath classPath = new ClassClassPath(this.getClass());
		ClassClassPath classPath = new ClassClassPath(cls);
		pool.insertClassPath(classPath);

		CtClass cc = pool.get(clazzName);
		CtMethod cm = cc.getDeclaredMethod(methodName);
		MethodInfo methodInfo = cm.getMethodInfo();
		CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
		LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
		if (attr == null) {
			// exception
		}
		String[] paramNames = new String[cm.getParameterTypes().length];
		int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
		for (int i = 0; i < paramNames.length; i++) {
			paramNames[i] = attr.variableName(i + pos); // paramNames即参数名
		}
		return paramNames;
	}


}
